/**
 * dependencies
 *http://luosimao.com/docs/api/30
 */
var https = require('https');
var querystring = require('querystring');
var debug = require("debug")("carclub:sms");


// var postData = {
//     mobile: '13712345678',
//     message: '夏季炎热，注意防暑降温【铁壳网络】'
// };

function sms(mobile, message, callback) {


    if (false) {
        debug("test send sms to %s for %s", mobile, message);
        return;
    }

    debug("send sms to %s for %s", mobile, message);

    callback = callback || function() {};

    var postData = {
        mobile:mobile,
        message:message
    };

    var content = querystring.stringify(postData);

    var options = {
        host:'sms-api.luosimao.com',
        path:'/v1/send.json',
        method:'POST',
        auth:'api:key-ccccdcc52a6e753377baff963fb2c75b',
        agent:false,
        rejectUnauthorized : false,
        headers:{
            'Content-Type' : 'application/x-www-form-urlencoded',
            'Content-Length' :content.length
        }
    };


    var request = https.request(options,function(response){
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            var resp = JSON.parse(chunk);
            debug("received sms platform response ", resp);
            if (resp.error < 0) {
                callback("短信发送失败：" + resp.msg);
            }
            callback(undefined);
        });
        response.on('end',function(){
            console.log('over');
        });
    });

    request.write(content);
    request.end();
}

exports.sms = sms;